<template>
  <div class="comment-list">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="comment-card">
        <template v-for="item in list" :key="item.id">
          <header-user
            v-if="item.user && item.updateTime"
            :user="item.user"
            :time="item.updateTime"
          />
          <div class="content" @click="onClickContent(item)">
            {{ item.content }}
          </div>
          <div
            class="reply"
            v-if="item.replyCount"
            @click="onShowReply(item.id)"
          >
            查看{{ item.replyCount }}条回复
          </div>
          <van-divider />
        </template>
      </div>
    </van-list>
    <van-action-sheet v-model:show="isShowActionShell" title="回复">
      <reply-card
        ref="replyRef"
        :comment-id="commentId"
        @push-data="onPushData"
      />
    </van-action-sheet>
  </div>
</template>

<script setup lang="ts">
import { getComments } from '../../../../service/comment'
import { commentsRes, replysRes } from '../../../../service/comment/types'
import HeaderUser from '../../../../components/header-user.vue'
import ReplyCard from './reply-card.vue'

const emit = defineEmits<{
  (e: 'replyComment', comment: Partial<commentsRes.Comment>): void
  (e: 'pushReplyData', reply: replysRes.Reply): void
}>()
const props = defineProps<{
  articleId: number | undefined
}>()
const list = ref<Partial<commentsRes.Comment>[]>([])
const loading = ref<boolean>(false)
const finished = ref<boolean>(false)
const isShowActionShell = ref<boolean>(false)
const totalCount = ref<number>(0)
const commentId = ref<number>(0)
const replyRef = ref<InstanceType<typeof ReplyCard>>()

const onPushData = (reply: replysRes.Reply) => {
  emit('pushReplyData', reply)
}
const onShowReply = (id?: number) => {
  if (!id) return
  commentId.value = id
  isShowActionShell.value = true
}
const onClickContent = (comment: Partial<commentsRes.Comment>) => {
  emit('replyComment', comment)
}
const onLoad = async () => {
  if (!props.articleId) return
  const res = await getComments(props.articleId, {
    offect: list.value.length,
    limit: 5
  })
  list.value.push(...res.data.comments)
  totalCount.value = res.data.totalCount
  loading.value = false
  if (list.value.length >= res.data.totalCount) {
    finished.value = true
  }
}

defineExpose({
  list,
  totalCount,
  replyRef
})
</script>

<style lang="scss" scoped>
.comment-list {
  .comment-card {
    .content {
      margin-left: 30px;
    }
    .reply {
      margin-top: 5px;
      margin-left: 30px;
      padding: 10px;
      border-radius: 5px;
      font-size: 13px;
      background-color: rgb(247, 247, 250);
    }
  }
}
</style>
